package com.tsfyun.common.base.util;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.tsfyun.common.base.dto.Result;
import com.tsfyun.common.base.enums.ResultCodeEnum;
import com.tsfyun.common.base.exception.ServiceException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.lang.Nullable;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Objects;

/**
 * @Description:
 * @Project:
 */
@Slf4j
public class ResultUtil {

    public static void checkRemoteResult(Result result) {
        checkRemoteResult(result,null);
    }

    public static void checkRemoteResult(Result result,@Nullable String errorMsg) {
        if (result == null) {
            throw new ServiceException(ResultCodeEnum.BUSINESS_ERROR);
        }
        boolean success = Objects.equals(result.getCode(),ResultCodeEnum.SUCCESS.getCode());
        if (!success) {
            log.error(StrUtil.format("远程调用获取数据失败:{}", JSONObject.toJSONString(result)));
            throw new ServiceException(result.getCode(), StringUtils.isEmpty(errorMsg) ? result.getMessage() : errorMsg);
        }
    }

    public static void errorBack(HttpServletResponse response, Result result) {
        PrintWriter writer = null;
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        try {
            writer = response.getWriter();
            writer.print(JSONObject.toJSONString(result));
        } catch (IOException e) {
            log.error("响应异常", e);
        } finally {
            if (writer != null) {
                writer.close();
            }
        }
    }

}